var dataSource = new Array();
//table的数据源
var table; //table对象
dataSource = [];
var  allData;
var  warehouseId = 0;

function getDCName() {
        var sel = document.getElementById("allDC"); //页面发货仓下拉框数据
        $.ajax({
            url: root.logistics.getAllWarehouse,
            cache: false, //禁用缓存
            type: "POST",
            dataType:"json",
            data:{},
            success: function(obj){
                for(var i=0;i<obj.data.length;i++){
                    $(sel).append('<span class="mr-40"><input name="radioname" class="mr-5 radio change_address" type="radio" value="'+obj.data[i].warehouse_code+'" data-val="'+obj.data[i].warehouse_name+'">'+obj.data[i].warehouse_name+'</span>');
                }
                $("input[type='radio'][name='radioname']").get(0).checked = true;
                getAllDCdate()
                list();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });

}

function getAllDCdate() {
    var DCname = $("input:radio[name='radioname']:checked").val();
    $.ajax({
        url: root.logistics.findDispatchScopeByPage,
        cache: false, //禁用缓存
        type: "POST",
        data: {
            pageSize: 20,
            pageNum: 1,
            warehouseCode:DCname
        },
        success: function(data){
            if(data.errorCode=="0"){
                allData = data;
                goodsList(allData);
            }else {
                layer.msg(data.errorMessage, {icon: 1,time:1000});
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}

function goodsList(dataList) {
    //console.log(allData)
    if(dataSource.length>0){
        dataSource.splice(0, dataSource.length); //清空数组
    }
    if(dataList.data.result!=null){
        $.each(dataList.data.result, function(i, field) {
            var rowData = new Array();
            rowData.push(field.transportModeType);
            rowData.push(field.areaName);
            /*rowData.push(field.status);*/
            rowData.push(field.createUser);
            rowData.push(field.createTime);

            rowData.push(field.id);
            rowData.push(field.areaCode);
            dataSource.push(rowData);
        });


    }
    rangeDataTable(dataSource);
    function rangeDataTable(dataSource) {

        console.log('总数据');
        console.log(dataSource);
        var dttable = $('#rangeTable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#rangeTable").DataTable({
            "autoWidth": false,
            "ordering": true,
            "searching": true,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [50, 25, 10, 5],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />"
            },
            data: dataSource,
            columnDefs: [{
                    "visible": true,
                    "targets": 0
                },

                {
                    "render": function(data, type, row, meta) {
                        if(row[0] == 40){
                            return '鑫方盛物流';
                        }else if (row[0] == 10) {
                            return '快递';
                        }else if (row[0] == 20) {
                            return '快运';
                        }else if (row[0] == 30) {
                            return '专车包车';
                        }
                    },
                    "targets": 0
                },


                {
                    "render": function(data, type, row, meta) { // 1,6
                        var idList =row[5].split(",");
                        var nameList = row[1].split(",");
                        var ulTop = '<ul class="radius text-l" id="ulList">';
                        var list="";
                        var ulfoot ='</ul>';
                        for(var i=0;i<idList.length;i++){
                            list += '<li class="f-l ml-10 liList" id="'+idList[i]+'"><span class="name">'+nameList[i]+'</span><sup style="color:#ff1b1b; cursor:pointer;">' +
                                '</sup></li>'
                        }

                        ulTop += list + ulfoot;
                        return ulTop;
                    },
                    "targets": 1
                },

                /*{
                    "render": function(data, type, row, meta) {
                        if(row[2] == 10){
                            return '有效';
                        }else{
                            return '无效';
                        }
                    },
                    "targets": 2
                },*/

                {
                    "render": function(data, type, row, meta) {
                        var val = '<a class="powerButton 135" onclick="relation_update(\'修改覆盖范围\','+row[0]+')"><span id="areaList" class="list">修改</span></a>&nbsp;&nbsp;&nbsp;<a class="powerButton 136" onclick="relation_delete(\'删除覆盖范围\','+row[0]+')"><span class="list">删除</span></a>';
                        return val;
                    },
                    "targets": 4
                },
            ]
        });
        //权限控制函数
        power()
    };
}

var thil;
var typeWayRoleID;
function area(title,thilr,rowId,rowType) {
    var liOne = $(thilr).prev().children()[0];
    if (rowType != 40){
        layer.msg('默认全国无法修改', {icon: 5,time:1000});
    }else{
        thil = thilr;
        typeWayRoleID = rowId
        $("#dizhi").modal("show");
        $(".addressTitle").html(title);
    }
}

function remove(thils,rowId,rowType){

    var liOne = $(thils).parent().parent()[0];
    if (liOne.id == 0 && rowType != 40){
        layer.msg('默认全国无法修改', {icon: 5,time:1000});
    }else {
        var lidata = $(thils).parent().parent().parent();
        $(thils).parent().parent().remove();
        //更改 单条的地址信息
        var liAll = $(lidata).children();

        var areaCode = "";
        var areaName = "";
        for (var i = 0; i < liAll.length; i++) {
            var cityid = liAll[i].id.split(",");
            areaCode = cityid[cityid.length - 1] + ',' + areaCode;
            areaName = $(liAll[i]).find('.name').text() + ',' + areaName;
        }

        var dataCity = allData.data.result;
        var dataCityOne = "";
        for (var i = 0; i < dataCity.length; i++) {
            if (rowId == dataCity[i].id) {
                dataCityOne = dataCity[i];
            }
        }
        var loginData = JSON.parse(web.readCookie("loginData"));
        var warehouseCode = dataCityOne.warehouseCode;
        var transportType = dataCityOne.transportType;
        var transportModeType = dataCityOne.transportModeType;
        var createUser = loginData.user.name; //创建人
            $.ajax({
                url: 'https://'+ window.location.host +'/api/admin/alogistics/updateDispatchScope.jhtml',
                cache: false, //禁用缓存
                type: "POST",
                data: {
                    warehouseCode: warehouseCode,
                    transportType: transportType,
                    transportModeType: transportModeType,
                    areaCode: areaCode,
                    areaName: areaName,
                    createUser: createUser
                },
                success: function(data){
                    if(data.sub_code == 0) {
                        layer.msg(data.sub_msg, {
                            icon: 1,
                            time: 1000,
                            end: function () {
                                getAllDCdate();
                            }
                        });
                    }else{
                        layer.msg(data.sub_msg, {icon: 5,time:2000});
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest);
                }
            });
    }

}


function saveCity() { //保存 选中的地址
    var cityName= $("#vueProvinceName").text()+" "+$("#vueCityName").text()+" "+$("#vueCountyName").text()+" "+$("#vueVillageName").text();
    var goodId = "";
    if($("#provinceId").text() != null){
        goodId = $("#provinceId").text()
    }
    if($("#cityId").text() != ""){
        goodId = goodId +","+$("#cityId").text()
    }
    if($("#countyId").text() != ""){
        goodId = goodId +","+$("#countyId").text()
    }
    if($("#villageId").text() != ""){
        goodId = goodId +","+$("#villageId").text()
    }
    if(goodId == ""){
        layer.msg('未选择地区', {icon: 5,time:1000});
        return;
    }
    console.log('iiidddd');
    console.log(goodId)
    var ulAll = $(thil).parent().find(".liList");
    var idOne = goodId.split(",");

    if (ulAll.length == 1){
        if (ulAll[0].id == 0){
            $(ulAll).parent().html('');
        }
    }

    for(var i=0;i<ulAll.length;i++){
        if(ulAll[i].id == idOne[idOne.length-1]){ //idOne[idOne.length-1]
            layer.msg('选择范围重复', {icon: 5,time:1000});
            return;
        }
    }


    $($(thil).prevAll()[0]).append('<li class="f-l ml-10 liList" id="'+goodId+'"><span class="name">'+cityName+'</span><sup style="color:#ff1b1b; cursor:pointer;">' +
        '<b onclick="remove(this)">x</b></sup></li>');

    var lidata = $(thil).prevAll()[0];
    var liAll = $(lidata).children();
    var areaCode = "";
    var areaName = "";
    console.log("shuchu")
    console.log(liAll)
    for(var i=0;i<liAll.length;i++){
        var cityid = liAll[i].id.split(",");
        areaCode = cityid[cityid.length-1]+','+areaCode;
        areaName = $(liAll[i]).find('.name').text()+','+areaName;
    }

    var dataCity = allData.data.result;
    var dataCityOne ="";
    for(var i=0;i<dataCity.length;i++){
        if (typeWayRoleID == dataCity[i].id){
            dataCityOne=dataCity[i];
        }
    }
    var loginData=JSON.parse(web.readCookie("loginData"));
    var warehouseCode = dataCityOne.warehouseCode;
    var transportType = dataCityOne.transportType;
    var transportModeType = dataCityOne.transportModeType;
    var createUser = loginData.user.name; //创建人

    $.ajax({
        url: root.logistics.updateDispatchScope,
        cache: false, //禁用缓存
        type: "POST",
        data: {
            warehouseCode: warehouseCode,
            transportType: transportType,
            transportModeType: transportModeType,
            areaCode: areaCode,
            areaName: areaName,
            createUser: createUser
        },
        success: function(data){
            if(data.sub_code == 0) {
                layer.msg(data.sub_msg, {
                    icon: 1,
                    time: 1000,
                    end: function () {
                        getAllDCdate();
                    }
                });
            }else{
                layer.msg(data.sub_msg, {icon: 5,time:2000});
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
    $("#dizhi").modal("hide");
}
function list(){
    $("[name='radioname']").change(function () {
        warehouseId = $("input:radio[name='radioname']:checked").val();
        getAllDCdate(warehouseId);
    })
}



$("#Pageselect").change(function () {
    //alert(this.value)
})

function relation_insert(title,url){
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}


function relation_update(title,typeWay) {

    var warhouseCode = $("input[name='radioname']:checked").val()
    var index = layer.open({
        type: 2,
        title: title,
        content: 'logisticsRange-update.html'+'?typeWay='+typeWay+'&warhouseCode='+warhouseCode
    });
    layer.full(index);
}

function relation_delete(title,typeWay) {
    var warehouseCode = $("input[name='radioname']:checked").val();

    $.ajax({
        url: 'https://'+ window.location.host +'/api/admin/alogistics/deleteDispatchScopeByWarehouseAndModetype.jhtml',
        cache: false, //禁用缓存
        type: "POST",
        dataType:'json',
        data: {
            warehouseCode: warehouseCode,
            transportModeType: typeWay,
        },
        success: function(result){
            console.log(result)
            if(result.sub_code == 0){
                layer.msg(result.sub_msg, {
                    icon: 1,
                    time: 1000,
                    end: function () {
                        getAllDCdate();
                    }
                });

            }else{
                layer.msg(result.sub_msg, {icon: 5,time:2000});
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest);
            //alert(XMLHttpRequest);
        }
    });

}

